package com.example.studentregistration.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.studentregistration.mapper.MajorMapper;
import com.example.studentregistration.pojo.Major;
import com.example.studentregistration.service.MajorService;
import com.example.studentregistration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class MajorServiceImpl implements MajorService {
    
    @Autowired
    private MajorMapper majorMapper;
    
    // 添加专业
    @Override
    public Result<?> insertMajor(Major major) {
        // 检查专业名称是否已存在
        Major existingMajor = majorMapper.queryMajorByName(major.getMajorName());
        if (existingMajor != null) {
            return Result.fail("专业名称已存在");
        }
        
        // 检查专业代码是否已存在
        existingMajor = majorMapper.queryMajorByCode(major.getMajorCode());
        if (existingMajor != null) {
            return Result.fail("专业代码已存在");
        }
        
        // 设置更新时间和默认启用状态
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        major.setUpdateTime(sdf.format(new Date()));
        if (major.getIsEnabled() == null) {
            major.setIsEnabled(1); // 默认启用
        }
        
        int result = majorMapper.insertMajor(major);
        if (result > 0) {
            return Result.success("添加成功");
        }
        return Result.fail("添加失败");
    }
    
    // 修改专业
    @Override
    public Result<?> updateMajor(Major major) {
        // 检查专业是否存在
        Major existingMajor = majorMapper.queryMajorById(major.getId());
        if (existingMajor == null) {
            return Result.fail("专业不存在");
        }
        
        // 检查专业名称是否重复（排除当前专业）
        Major nameMajor = majorMapper.queryMajorByName(major.getMajorName());
        if (nameMajor != null && !nameMajor.getId().equals(major.getId())) {
            return Result.fail("专业名称已存在");
        }
        
        // 检查专业代码是否重复（排除当前专业）
        Major codeMajor = majorMapper.queryMajorByCode(major.getMajorCode());
        if (codeMajor != null && !codeMajor.getId().equals(major.getId())) {
            return Result.fail("专业代码已存在");
        }
        
        // 设置修改时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        major.setUpdateTime(sdf.format(new Date()));
        
        int result = majorMapper.updateMajor(major);
        if (result > 0) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败");
    }
    
    // 删除专业
    @Override
    public Result<?> deleteMajor(Integer id) {
        // 检查专业是否存在
        Major existingMajor = majorMapper.queryMajorById(id);
        if (existingMajor == null) {
            return Result.fail("专业不存在");
        }
        
        int result = majorMapper.deleteMajor(id);
        if (result > 0) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }
    
    // 批量删除专业
    @Override
    public int batchDeleteMajor(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        return majorMapper.batchDeleteMajor(ids);
    }
    
    // 查询所有专业（分页）
    @Override
    public Page queryAllMajors(Integer currentPage, Integer pageSize) {
        Page<Major> page = PageHelper.startPage(currentPage, pageSize);
        majorMapper.queryAllMajors();
        return page;
    }
    
    // 根据ID查询专业
    @Override
    public Result<Major> queryMajorById(Integer id) {
        Major major = majorMapper.queryMajorById(id);
        if (major != null) {
            return Result.success(major);
        }
        return Result.fail("专业不存在");
    }
    
    // 根据专业名称查询专业
    @Override
    public Result<Major> queryMajorByName(String majorName) {
        Major major = majorMapper.queryMajorByName(majorName);
        if (major != null) {
            return Result.success(major);
        }
        return Result.fail("专业不存在");
    }
    
    // 根据专业代码查询专业
    @Override
    public Result<Major> queryMajorByCode(String majorCode) {
        Major major = majorMapper.queryMajorByCode(majorCode);
        if (major != null) {
            return Result.success(major);
        }
        return Result.fail("专业不存在");
    }
    
    // 导出专业信息
    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 查询所有专业信息
        List<Major> majors = majorMapper.queryAllMajors();
        
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(majors, true);
        
        // 设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("专业信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        
        // 获取输出流对象
        ServletOutputStream os = response.getOutputStream();
        writer.flush(os, true);
        
        // 关闭writer，释放内存
        writer.close();
        
        // 关闭输出Servlet流
        IoUtil.close(os);
    }
}